<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header"></el-header>
<!--      <div class="router">-->
<!--        <p>首页 > 商品名</p>-->
<!--      </div>-->
      <!-- 面包屑 -->
      <div class="bread-container">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: ''}">{{ clothesDetail?.clName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-container class="goodsRelative">
        <el-aside class="aside">
          <div class="demo-image__placeholder">
            <div class="block">
              <el-image :src="'http://localhost:8080' + (clothesDetail?.clImagePath || '')">
                <template #placeholder>
                  <div class="image-slot">Loading<span class="dot">...</span></div>
                </template>
              </el-image>
            </div>
          </div>
        </el-aside>
        <el-main class="main">
          <el-descriptions column="1">
            <el-descriptions-item>
              <span class="goodsName">{{ clothesDetail?.clName || '商品名称' }}</span>
            </el-descriptions-item>
            <el-descriptions-item>
              <span class="goodsPrice">￥{{ clothesDetail?.clPrice || '0.00' }}</span>
            </el-descriptions-item>
            <el-descriptions-item>{{ clothesDetail?.clDescribe || '商品描述' }}</el-descriptions-item>
            <el-descriptions-item>
              <el-tag size="small" class="tagCss">{{ clothesDetail?.clType || '服装类型' }}</el-tag>
            </el-descriptions-item>

<!--            购物车-->
            <el-descriptions-item label="数量">
              <el-input-number v-model="num" :min="1" :max="10" @change="handleChangeNum" class="custom-input-number"/>
              <el-button type="danger" class="addToCart" @click="handleAddToCart">加入购物车</el-button>
              <img :src="iconUrl" class="icon" @click="toggleCollect" />
            </el-descriptions-item>
          </el-descriptions>
        </el-main>
      </el-container>

<!--      商品详情图-->
      <div class="common-layout2">
        <el-container>
          <el-header>
            <span>商品详情</span>
          </el-header>
          <el-main>
            <div class="demo-image__lazy">
              <el-image v-for="url in urls" :key="url" :src="'http://localhost:8080' + url" lazy />
              <div v-if="!urls.length" class="no-images">
                敬请期待
              </div>
            </div>
          </el-main>
        </el-container>
      </div>

    </el-container>
  </div>
</template>

<script setup>
// 导入 addToCart 方法
import {useCartStore} from "@/store/cartStore";

const cartStore = useCartStore()
import { ref,onMounted ,nextTick} from 'vue'
import { useRoute } from 'vue-router';  // 用来获取 URL 中的参数
import { ElMessage } from 'element-plus'
import axios from 'axios';
import collectIcon from '@/assets/images/collect.png';
import collectSelectedIcon from '@/assets/images/collectSelected.png';

const route = useRoute(); // 获取路由信息
const clNo = route.params.clNo; // 获取 URL 中的 clNo 参数，用于查询服装的编号

// 用于存储服装详情数据
const clothesDetail = ref({
  clImagePath: '',  // 设置为一个空字符串或默认图片
  clName: '',
  clPrice: 0,
  clDescribe: '',
  clType: '',
  detailImages: [],
  // 可以继续添加其他字段的默认值
});

//商品图片
const src =ref('')
//数据库传递商品详情图
const urls= ref([]);

//用于跟踪是否已收藏
const isCollect = ref(false);

// 图标的两个 URL (收藏和未收藏状态)
const iconUrl = ref(collectIcon); // 默认未收藏的图标

//加载商品详情
const fetchClothesDetail = async () =>{
  try {
    const response = await axios.get('/api/detail',{
      params:{clNo:clNo}, //传递服装编号
    });

    console.log('返回的商品详情:', response.data); // 打印返回的数据，确认数据结构

    if (response.data.code === 200){
      const data = response.data.data;  //获取返回的数据
      clothesDetail.value = data; //复制给clothDetail
      urls.value = data.detailImagePaths || [];

      src.value = data.clImagePath || '';
    }else {
      ElMessage.error(response.data.msg || '商品详情加载失败');
    }
  }catch (error){
    console.log('Error fetching cloths detail:',error);
    ElMessage.error('商品详情加载失败，请稍后再试');
  }
};

// 判断是否已收藏
const checkIfFavorite = async () => {
  const userInfo = sessionStorage.getItem('CurUser');
  if (!userInfo) {
    ElMessage.error('请先登录');
    return;
  }

  const user = JSON.parse(userInfo);
  const userId = user.userId;

  try {
    const response = await axios.get('/api/favorite/isFavorite', {
      params: { userId: userId, clNo: clNo },
    });

    console.log('收藏状态:', response.data); // 打印返回的收藏状态

    if (response.data.code === 200) {
      isCollect.value = response.data.data; // 设置收藏状态
      iconUrl.value = isCollect.value ? collectSelectedIcon : collectIcon; // 根据收藏状态切换图标
    } else {
      ElMessage.error(response.data.msg || '检查收藏状态失败');
    }
  } catch (error) {
    console.log('Error checking favorite status:', error);
    ElMessage.error('检查收藏状态失败，请稍后再试');
  }
};

//添加商品到购物车
const handleAddToCart = async () =>{
  const userInfo = sessionStorage.getItem('CurUser');
  if (!userInfo) {
    ElMessage.error('请先登录');
    return;
  }

  const user = JSON.parse(userInfo);
  const userId = user.userId;

  const clName = clothesDetail.value.clName;
  const clPrice = clothesDetail.value.clPrice;

  //  调用addToCart方法
  cartStore.addCart(userId,clNo,num.value,clName,clPrice);
}

//在页面加载时获取服装详情
onMounted(()=>{
  checkIfFavorite();

  if (clNo){
    fetchClothesDetail();
  }else {
    ElMessage.error('无效的商品编号');
  }

  // 使用nextTick确保DOM更新完成后设置滚动位置
  nextTick(() => {
    const container = document.querySelector('.goodsRelative'); // 选择页面内的滚动容器
    if (container) {
      container.scrollTop = 0; // 滚动到顶部
    }
  });
});

const value = ref('')
const options = ref([]);

const warn = () => {
  ElMessage({
    message: '请补全信息！',
    type: 'warning',
  })
}

//添加购物车
const num = ref(1);
const handleChangeNum = (value) =>{
  console.log(value)
}

//切换收藏状态
const toggleCollect = async () =>{
  const userInfo = sessionStorage.getItem('CurUser');
  if (!userInfo) {
    ElMessage.error('请先登录');
    return;
  }
  const user = JSON.parse(userInfo);
  const userId = user.userId;

  try {
    if (isCollect.value) {
      // 如果已经收藏，调用后端接口删除收藏
      const response = await axios.delete('/api/favorite/delete', {
        params: { userId: userId, clNo: clNo }
      });

      if (response.data.code === 200) {
        isCollect.value = false;
        iconUrl.value = collectIcon;
        ElMessage.success('已取消收藏');
      } else {
        ElMessage.error(response.data.msg || '取消收藏失败');
      }
  }else{
      // 如果未收藏，调用后端接口添加收藏
      const response = await axios.post('/api/favorite/add', null, {
        params: { userId: userId, clNo: clNo }
      });

      if (response.data.code === 200) {
        isCollect.value = true;
        iconUrl.value = collectSelectedIcon;
        ElMessage.success('已收藏');
      } else {
        ElMessage.error(response.data.msg || '添加收藏失败');
      }
    }
  }catch (error){
    console.log('Error toggling favorite:', error);
    ElMessage.error('收藏操作失败，请稍后再试');
  }
};

</script>

<style scoped>
.header{
  display: flex;
  height: 0px;
  justify-content: space-between;
  align-items: center;
  background-color: #333;
}
/*.router{*/
/*  margin: 20px;*/
/*}*/
/*.router p{*/
/*  color: gray;*/
/*}*/

.bread-container {
  color: #666;
  width: 90%;
  margin: 20px auto;
}

::v-deep .el-breadcrumb__item .el-breadcrumb__inner a:hover,
::v-deep .el-breadcrumb__item .el-breadcrumb__inner:hover {
  color: #e180a4; /* 设置 hover 时的颜色为橙色 */
  cursor: pointer; /* 鼠标悬停时显示手型图标 */
}

/*aside样式*/
.aside{
  width: 40%;
  /*background-color: lightgoldenrodyellow;*/
}
.demo-image__placeholder {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 30px 0;
}

.demo-image__placeholder .block {
  padding: 30px 0;
  text-align: center;
  /*border-right: solid 1px var(--el-border-color);*/
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  vertical-align: top;
}
/*.demo-image__placeholder .demonstration {*/
/*  display: block;*/
/*  color: var(--el-text-color-secondary);*/
/*  font-size: 14px;*/
/*  margin-bottom: 20px;*/
/*}*/
.demo-image__placeholder .el-image {
  padding: 0 5px;
  max-width: 200px;
  max-height: 300px;
}

.demo-image__placeholder.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.demo-image__placeholder .dot {
  animation: dot 2s infinite steps(3, start);
  overflow: hidden;
}

/*main样式*/
.main{
  /*background-color: lightblue;*/
}

.goodsName{
  color: black;
  font-weight: bold;
  /*font-size: 22px;*/
}

.tagCss{
  background-color: #ffeaeb;
  color: #ff84b0;
  border: 1px solid #ffeaeb;
}

.icon{
  cursor: pointer;
  margin-left: 20px;
  /*width: 20px;*/
  /*height: 20px;*/
  transition: color 0.3s ease;
  vertical-align: middle;
}

.goodsPrice{
  color: #CF4444;
  /*font-size: 20px;*/
  font-weight: bold;
}

/*.el-input-number .custom-input-number{*/
/*  border-color: #ffd2d8;*/
/*}*/

.addToCart{
  /*margin-left: 20px;*/
  background-color: #ffd2d8;
  color: black;
  font-weight: bold !important;
  border: #ffd2d8;
}

.addToCart:hover {
  transform:scale(1.1);
}

.goodsRelative{
  display: flex;
  flex-direction: row; /* 横向排列 */
  justify-content: space-between; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin: 15px auto;
  background-color: white;
  width: 90%;
}

/*商品详情*/
.common-layout2{
  background-color: white;
  margin: 15px auto;
  width: 90%;
}

.common-layout2 ::v-deep .el-header{
  align-content: center;
  border-bottom: 1px solid #ddd;
}

.common-layout2 ::v-deep .el-header span{
  font-size: 22px;
  vertical-align: center;
}

/*商品详情图样式*/
.demo-image__lazy {
  height: 600px;
  overflow-y: auto;
}
.demo-image__lazy .el-image {
  display: block;
  min-height: 200px;
  margin-bottom: 10px;
}
.demo-image__lazy .el-image:last-child {
  margin-bottom: 0;
}

.no-images{
  font-size: 18px;
  color: gray;
  margin-top: 20px;
}

/*通用样式，保证背景颜色始终应用*/
.common-layout{
  background-color: #f5f5f5 !important;
}

/*响应式布局*/
/* 超小屏幕（手机小于768px）设置宽度为100% */
@media (max-width: 767px) {
  .common-layout{
    width: 100%;
  }
  .goodsRelative,
  .common-layout2 {
    width: 90%;
  }

  /* 商品图和商品介绍竖排 */
  .goodsRelative {
    display: block; /* 设置为块级布局，竖直排列 */
  }

  /* 调整商品图和商品介绍的样式 */
  .aside {
    width: 100%; /* 商品图宽度100% */
    margin-bottom: 20px; /* 为了分隔商品图和商品介绍 */
  }

  .main {
    width: 100%; /* 商品介绍宽度100% */
  }

  .router p {
    font-size: 14px;
  }

  .goodsName {
    font-size: 18px;
  }

  .goodsPrice {
    font-size: 18px;
  }

  .icon {
    width: 18px;
    height: 18px;
  }

  .addToCart {
    margin-left: 10px;
  }
}

/* 小屏幕（平板，大于等于768px）设置宽度为750px */
@media (min-width: 768px) and (max-width: 991px) {
  .common-layout{
    width: 100%;
  }
  .goodsRelative,
  .common-layout2 {
    width: 90%;
    margin: 20px auto;
  }

  .goodsRelative {
    display: flex; /* 使用flex布局，左右排列 */
    justify-content: space-between;
    flex-direction: row; /* 横向排列 */
  }

  .aside {
    width: 45%; /* 左侧商品图占45%宽度 */
  }

  .main {
    width: 50%; /* 右侧商品介绍占50%宽度 */
  }

  .router p {
    font-size: 16px;
  }

  .goodsName {
    font-size: 20px;
  }

  .goodsPrice {
    font-size: 20px;
  }

  .icon {
    width: 22px;
    height: 22px;
  }

  .addToCart {
    margin-left: 15px;
  }
}

/* 中等屏幕（桌面显示器，大于等于992px）设置宽度为970px */
@media (min-width: 992px) and (max-width: 1199px) {
  .common-layout{
    width: 100%;
  }
  .goodsRelative,
  .common-layout2 {
    width: 90%;
    margin: 20px auto;
  }

  .goodsRelative {
    display: flex; /* 使用flex布局，左右排列 */
    justify-content: space-between;
  }

  .aside {
    width: 30%; /* 左侧商品图占30%宽度 */
  }

  .main {
    width: 70%; /* 右侧商品介绍占70%宽度 */
  }

  .router p {
    font-size: 18px;
  }

  .goodsName {
    font-size: 22px;
  }

  .goodsPrice {
    font-size: 22px;
  }

  .icon {
    width: 24px;
    height: 24px;
    transition: 0.3s ease;
  }

  .addToCart {
    margin-left: 20px;
  }
}

/* 大屏幕（大桌面显示器，大于等于1200px）宽度设置为1170px */
@media (min-width: 1200px) {
  .common-layout{
    width: 100%;
  }
  .goodsRelative,
  .common-layout2 {
    width: 90%;
    margin: 20px auto;
  }

  .goodsRelative {
    display: flex; /* 使用flex布局，左右排列 */
    justify-content: space-between;
    margin: 0px auto;
  }

  .aside {
    width: 30%; /* 左侧商品图占45%宽度 */
  }

  .main {
    width: 70%; /* 右侧商品介绍占50%宽度 */
  }

  .router p {
    font-size: 18px;
  }

  .goodsName {
    font-size: 24px;
  }

  .goodsPrice {
    font-size: 24px;
  }

  .icon {
    width: 26px;
    height: 26px;
  }

  .addToCart {
    margin-left: 25px;
  }
}

</style>